<template>
  <ResponsiveLayout 
    layout="default" 
    :show-sidebar="false" 
    :safe-area="true"
    content-padding="20px"
  >
    <!-- 移动端导航 -->
    <MobileNavigation
      v-if="isMobile"
      :title="'个人中心'"
      :show-back="true"
      @back="$router.go(-1)"
    />

    <!-- 桌面端头部 -->
    <template #header>
      <header v-if="!isMobile" class="profile-header">
        <div class="header-content">
          <div class="header-left">
            <el-button type="text" @click="$router.go(-1)">
              <el-icon><ArrowLeft /></el-icon>
              返回
            </el-button>
            <h1>个人中心</h1>
          </div>
        </div>
      </header>
    </template>

    <!-- 主要内容区域 -->
    <div class="profile-container" :class="{ 'mobile-layout': isMobile }">
      <!-- 用户信息卡片 -->
      <div class="user-info-card">
        <div class="user-avatar-section">
          <div class="avatar-container">
            <OptimizedImage 
              :src="userStore.userInfo?.avatar || '/OIP.webp'" 
              alt="用户头像" 
              class="user-avatar" 
              :lazy="false" 
              :width="80" 
              :height="80" 
            />
            <el-button type="primary" size="small" class="change-avatar-btn">
              <el-icon><Camera /></el-icon>
              更换头像
            </el-button>
          </div>
          <div class="user-basic-info">
            <h2>{{ userStore.userInfo?.realName || '未设置姓名' }}</h2>
            <p class="username">@{{ userStore.userInfo?.username }}</p>
            <p class="join-date">加入时间：{{ formatDate(userStore.userInfo?.createdAt) }}</p>
          </div>
        </div>
      </div>

      <!-- 个人信息表单 -->
      <div class="profile-form-card">
        <div class="card-header">
          <h3>个人信息</h3>
          <el-button 
            v-if="!isEditing" 
            type="primary" 
            @click="startEdit"
          >
            <el-icon><Edit /></el-icon>
            编辑
          </el-button>
          <div v-else class="edit-actions">
            <el-button @click="cancelEdit">取消</el-button>
            <el-button 
              type="primary" 
              :loading="saving" 
              @click="saveProfile"
            >
              保存
            </el-button>
          </div>
        </div>
        
        <el-form
          ref="profileFormRef"
          :model="profileForm"
          :rules="profileRules"
          label-width="100px"
          class="profile-form"
        >
          <el-form-item label="真实姓名" prop="realName">
            <el-input
              v-model="profileForm.realName"
              :disabled="!isEditing"
              placeholder="请输入真实姓名"
            />
          </el-form-item>
          
          <el-form-item label="用户名" prop="username">
            <el-input
              v-model="profileForm.username"
              :disabled="!isEditing"
              placeholder="请输入用户名"
            />
          </el-form-item>
          
          <el-form-item label="手机号" prop="phone">
            <el-input
              v-model="profileForm.phone"
              :disabled="!isEditing"
              placeholder="请输入手机号"
            />
          </el-form-item>
          
          <el-form-item label="邮箱" prop="email">
            <el-input
              v-model="profileForm.email"
              :disabled="!isEditing"
              placeholder="请输入邮箱地址"
            />
          </el-form-item>
          
          <el-form-item label="性别" prop="gender">
            <el-radio-group v-model="profileForm.gender" :disabled="!isEditing">
              <el-radio label="male">男</el-radio>
              <el-radio label="female">女</el-radio>
              <el-radio label="other">其他</el-radio>
            </el-radio-group>
          </el-form-item>
          
          <el-form-item label="出生日期" prop="birthDate">
            <el-date-picker
              v-model="profileForm.birthDate"
              type="date"
              placeholder="选择出生日期"
              :disabled="!isEditing"
              style="width: 100%"
            />
          </el-form-item>
          
          <el-form-item label="身份证号" prop="idCard">
            <el-input
              v-model="profileForm.idCard"
              :disabled="!isEditing"
              placeholder="请输入身份证号"
              show-password
            />
          </el-form-item>
          
          <el-form-item label="紧急联系人" prop="emergencyContact">
            <el-input
              v-model="profileForm.emergencyContact"
              :disabled="!isEditing"
              placeholder="请输入紧急联系人姓名"
            />
          </el-form-item>
          
          <el-form-item label="联系人电话" prop="emergencyPhone">
            <el-input
              v-model="profileForm.emergencyPhone"
              :disabled="!isEditing"
              placeholder="请输入紧急联系人电话"
            />
          </el-form-item>
          
          <el-form-item label="地址" prop="address">
            <el-input
              v-model="profileForm.address"
              type="textarea"
              :rows="3"
              :disabled="!isEditing"
              placeholder="请输入详细地址"
            />
          </el-form-item>
        </el-form>
      </div>

      <!-- 账户安全 -->
      <div class="security-card">
        <div class="card-header">
          <h3>账户安全</h3>
        </div>
        
        <div class="security-items">
          <div class="security-item">
            <div class="security-info">
              <el-icon><Lock /></el-icon>
              <div>
                <div class="security-title">登录密码</div>
                <div class="security-desc">定期更换密码，保护账户安全</div>
              </div>
            </div>
            <el-button type="text" @click="showChangePassword = true">
              修改
            </el-button>
          </div>
          
          <div class="security-item">
            <div class="security-info">
              <el-icon><Phone /></el-icon>
              <div>
                <div class="security-title">手机绑定</div>
                <div class="security-desc">{{ userStore.userInfo?.phone || '未绑定' }}</div>
              </div>
            </div>
            <el-button type="text">
              {{ userStore.userInfo?.phone ? '更换' : '绑定' }}
            </el-button>
          </div>
          
          <div class="security-item">
            <div class="security-info">
              <el-icon><Message /></el-icon>
              <div>
                <div class="security-title">邮箱绑定</div>
                <div class="security-desc">{{ userStore.userInfo?.email || '未绑定' }}</div>
              </div>
            </div>
            <el-button type="text">
              {{ userStore.userInfo?.email ? '更换' : '绑定' }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 其他操作 -->
      <div class="actions-card">
        <div class="action-item danger" @click="handleLogout">
          <el-icon><SwitchButton /></el-icon>
          <span>退出登录</span>
        </div>
      </div>
    </div>

    <!-- 修改密码对话框 -->
    <el-dialog
      v-model="showChangePassword"
      title="修改密码"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
      >
        <el-form-item label="当前密码" prop="currentPassword">
          <el-input
            v-model="passwordForm.currentPassword"
            type="password"
            placeholder="请输入当前密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input
            v-model="passwordForm.newPassword"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="passwordForm.confirmPassword"
            type="password"
            placeholder="请确认新密码"
            show-password
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showChangePassword = false">取消</el-button>
        <el-button 
          type="primary" 
          :loading="changingPassword" 
          @click="changePassword"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </ResponsiveLayout>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../stores/user'
import { useResponsive } from '../utils/responsive'
import { ElMessage, ElMessageBox } from 'element-plus'
import ResponsiveLayout from '../components/ResponsiveLayout.vue'
import MobileNavigation from '../components/MobileNavigation.vue'
import OptimizedImage from '../components/OptimizedImage.vue'
import {
  ArrowLeft,
  Edit,
  Camera,
  Lock,
  Phone,
  Message,
  SwitchButton
} from '@element-plus/icons-vue'

const router = useRouter()
const userStore = useUserStore()
const { isMobile } = useResponsive()

// 表单引用
const profileFormRef = ref()
const passwordFormRef = ref()

// 编辑状态
const isEditing = ref(false)
const saving = ref(false)

// 修改密码相关
const showChangePassword = ref(false)
const changingPassword = ref(false)

// 个人信息表单
const profileForm = reactive({
  realName: '',
  username: '',
  phone: '',
  email: '',
  gender: '',
  birthDate: '',
  idCard: '',
  emergencyContact: '',
  emergencyPhone: '',
  address: ''
})

// 密码修改表单
const passwordForm = reactive({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单验证规则
const profileRules = {
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 10, message: '姓名长度在 2 到 10 个字符', trigger: 'blur' }
  ],
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '用户名长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
  ],
  idCard: [
    { pattern: /^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/, message: '请输入正确的身份证号格式', trigger: 'blur' }
  ],
  emergencyPhone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号格式', trigger: 'blur' }
  ]
}

const passwordRules = {
  currentPassword: [
    { required: true, message: '请输入当前密码', trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认新密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error('两次输入密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  return new Date(dateString).toLocaleDateString('zh-CN')
}

// 开始编辑
const startEdit = () => {
  isEditing.value = true
  // 复制当前用户信息到表单
  Object.assign(profileForm, {
    realName: userStore.userInfo?.realName || '',
    username: userStore.userInfo?.username || '',
    phone: userStore.userInfo?.phone || '',
    email: userStore.userInfo?.email || '',
    gender: userStore.userInfo?.gender || '',
    birthDate: userStore.userInfo?.birthDate || '',
    idCard: userStore.userInfo?.idCard || '',
    emergencyContact: userStore.userInfo?.emergencyContact || '',
    emergencyPhone: userStore.userInfo?.emergencyPhone || '',
    address: userStore.userInfo?.address || ''
  })
}

// 取消编辑
const cancelEdit = () => {
  isEditing.value = false
  // 重置表单
  Object.assign(profileForm, {
    realName: userStore.userInfo?.realName || '',
    username: userStore.userInfo?.username || '',
    phone: userStore.userInfo?.phone || '',
    email: userStore.userInfo?.email || '',
    gender: userStore.userInfo?.gender || '',
    birthDate: userStore.userInfo?.birthDate || '',
    idCard: userStore.userInfo?.idCard || '',
    emergencyContact: userStore.userInfo?.emergencyContact || '',
    emergencyPhone: userStore.userInfo?.emergencyPhone || '',
    address: userStore.userInfo?.address || ''
  })
}

// 保存个人信息
const saveProfile = async () => {
  if (!profileFormRef.value) return
  
  try {
    const valid = await profileFormRef.value.validate()
    if (!valid) return
    
    saving.value = true
    const result = await userStore.updateUserInfo(profileForm)
    
    if (result.success) {
      ElMessage.success('个人信息更新成功')
      isEditing.value = false
    } else {
      ElMessage.error(result.message || '更新失败，请稍后重试')
    }
  } catch (error) {
    console.error('更新个人信息失败:', error)
    ElMessage.error('更新失败，请稍后重试')
  } finally {
    saving.value = false
  }
}

// 修改密码
const changePassword = async () => {
  if (!passwordFormRef.value) return
  
  try {
    const valid = await passwordFormRef.value.validate()
    if (!valid) return
    
    changingPassword.value = true
    
    // TODO: 调用修改密码API
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('密码修改成功')
    showChangePassword.value = false
    
    // 重置表单
    Object.assign(passwordForm, {
      currentPassword: '',
      newPassword: '',
      confirmPassword: ''
    })
  } catch (error) {
    console.error('修改密码失败:', error)
    ElMessage.error('修改密码失败，请稍后重试')
  } finally {
    changingPassword.value = false
  }
}

// 退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要退出登录吗？',
      '提示',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    userStore.logout()
    ElMessage.success('已退出登录')
    router.push('/login')
  } catch {
    // 用户取消
  }
}

// 初始化表单数据
const initFormData = () => {
  Object.assign(profileForm, {
    realName: userStore.userInfo?.realName || '',
    username: userStore.userInfo?.username || '',
    phone: userStore.userInfo?.phone || '',
    email: userStore.userInfo?.email || '',
    gender: userStore.userInfo?.gender || '',
    birthDate: userStore.userInfo?.birthDate || '',
    idCard: userStore.userInfo?.idCard || '',
    emergencyContact: userStore.userInfo?.emergencyContact || '',
    emergencyPhone: userStore.userInfo?.emergencyPhone || '',
    address: userStore.userInfo?.address || ''
  })
}

onMounted(() => {
  initFormData()
})
</script>

<style scoped>
.profile-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
}

.mobile-layout {
  padding: 16px;
  padding-top: 70px;
}

.profile-header {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 60px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-left h1 {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #2c3e50;
}

.user-info-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.user-avatar-section {
  display: flex;
  align-items: center;
  gap: 20px;
}

.avatar-container {
  position: relative;
  text-align: center;
}

.user-avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #409eff;
}

.change-avatar-btn {
  margin-top: 8px;
  font-size: 12px;
}

.user-basic-info h2 {
  margin: 0 0 8px 0;
  font-size: 24px;
  font-weight: 600;
  color: #2c3e50;
}

.username {
  color: #7f8c8d;
  margin: 0 0 4px 0;
  font-size: 14px;
}

.join-date {
  color: #95a5a6;
  margin: 0;
  font-size: 12px;
}

.profile-form-card,
.security-card,
.actions-card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #eee;
}

.card-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #2c3e50;
}

.edit-actions {
  display: flex;
  gap: 8px;
}

.profile-form {
  max-width: 600px;
}

.security-items {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.security-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
}

.security-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.security-title {
  font-weight: 600;
  color: #2c3e50;
  margin-bottom: 4px;
}

.security-desc {
  font-size: 12px;
  color: #7f8c8d;
}

.action-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  border-radius: 8px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.action-item:hover {
  background: #f8f9fa;
}

.action-item.danger {
  color: #e74c3c;
}

.action-item.danger:hover {
  background: #fdf2f2;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-avatar-section {
    flex-direction: column;
    text-align: center;
    gap: 16px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .edit-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .security-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
}
</style>